package common

import (
	"gin-demo/model"
	"github.com/dgrijalva/jwt-go"
	"time"
)
/**
生成和解析 token
 */
var jwtKey = []byte("a_secret_crect")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

// ReleaseToken 根据用户id得到token
func ReleaseToken(user model.User) (string, error) {
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(7*24*time.Hour).Unix(),//过期时间
			IssuedAt: time.Now().Unix(),//发放时间
			Issuer: "bxrhhy",//发放人
			Subject: "user token",//主题

		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	tokenString, err := token.SignedString(jwtKey)
	if err!=nil{
		return "",err
	}
	return tokenString,nil
}

// ParseToken 解析token
func ParseToken(tokenString string) (*jwt.Token,*Claims,error) {
	claims := &Claims{}
	token,err:=jwt.ParseWithClaims(tokenString,claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey,nil
	})
	return token,claims,err
}